package com.example.demo.services;

import com.example.demo.entity.Buyer.BuyPlanBill;
import com.example.demo.entity.Buyer.BuyPlanBillDetail;
import com.example.demo.repository.BuyPlanBillRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class BuyPlanBillService {
    private final BuyPlanBillRepository buyPlanBillRepository;

    public BuyPlanBillService(BuyPlanBillRepository buyPlanBillRepository) {
        this.buyPlanBillRepository = buyPlanBillRepository;
    }

    public List<BuyPlanBill> getAllBuyPlanBills() {
        return (List<BuyPlanBill>) buyPlanBillRepository.findAll();
    }

    public List<BuyPlanBill> getBuyPlanBill(String billNo) {
        //System.out.println("2:" + billNo);
        return buyPlanBillRepository.findByBillNo(billNo);
    }

    public List<BuyPlanBillDetail> getDetail(String billNo) {
        return  buyPlanBillRepository.findDetail(billNo);
    }

    public List<Object> getBuyer() {
        List<Object[]> a = buyPlanBillRepository.getBuyer();
        List<Object> buyerList = new ArrayList<>();
        ObjectMapper objectMapper = new ObjectMapper();
        for (Object[] row : a) {
            String value = (String) row[0];
            String label = (String) row[1];
            try {
                HashMap<String,String> map = new HashMap<>();
                map.put("value",value);
                map.put("label",label);
                buyerList.add(objectMapper.writeValueAsString(map));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            //buyerList.add("{\"label\":\"" + label + "\", \"value\":\"" + value + "\"}");
            //[label:郭素坤,value:CG0001, label:闫书凯,value:CG0002, label:田丛丛,value:CG0003]
        }
        //System.out.println(buyerList);
        return buyerList;
    }

    public int setForm(String billNo, Date planDate, String buyerCode, String remark){
        int num = -1;
        try {
            if (buyPlanBillRepository.getBillNo(billNo) != null) {
                buyPlanBillRepository.setForm(billNo, planDate, buyerCode, remark);
                num = 1;
            }else if (buyPlanBillRepository.getBillNo(billNo) == null) {
                buyPlanBillRepository.addForm(billNo, planDate, buyerCode, remark);
                num = 2;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        //System.out.println(num);
        //1 更新成功
        //2 添加成功
        //-1 执行失败
        return num;
    }
}
